package com.ccx.library.util;

import com.ccx.library.module.menu.entity.Menu;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 菜单工具
 */
@Component
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MenuUtil {


    public List<Menu> list = new ArrayList<>();

    /**
     * 父节点id
     */
    public final static Integer ROOT=0;
    /**
     * 菜单
     */
    public List<Menu> DynamicsMenusProcess(List<Menu> menuList){
        setList(menuList);
        List<Menu> treeNodes = new ArrayList<>();
        getRootNode().forEach(Tree->{
            Tree = buildChildrenTree(Tree);
            treeNodes.add(Tree);
        } );
        return treeNodes;
    }

    /**
     * 获取父节点
     */
    public List<Menu> getRootNode(){
        List<Menu> menuList = new ArrayList<>();
        list.forEach(item->{
            if (ROOT.equals(Integer.valueOf(item.getParent_id()))){
                menuList.add(item);
            }
        });
        return menuList;
    }
    /**
     * 递归children节点
     */
    public Menu buildChildrenTree(Menu treeNode){
        List<Menu> childrenListNode = new ArrayList<>();
        list.forEach(menu -> {
            if (menu.getParent_id().equals(treeNode.getMenu_id())){
                childrenListNode.add(buildChildrenTree(menu));
            }
        });
        treeNode.setChildren(childrenListNode);
        return treeNode;
    }
}